package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    public Utils(String url){
        createDriver();
        driver.get(url);
    }

    private static void createDriver() {
        if(driver == null){
            WebDriverManager.chromedriver().setup();

            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            // 隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
    }

    public static void getScreenShot(String testcase) throws IOException {

        // 1. 创建截图文件
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // 2. 通过时间戳实现两级目录
        SimpleDateFormat dirFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat fileFormat = new SimpleDateFormat("hhmmssSS");

        String dir = "./src/test/image/" + dirFormat.format(System.currentTimeMillis()) + "/";
        String fileName = testcase + "-" + fileFormat.format(System.currentTimeMillis()) + ".png";

        System.out.println(dir + fileName);

        // 3. 生成文件
        FileUtils.copyFile(srcFile, new File(dir + fileName));
    }
}
